<template>
  <sc-drawer v-model="visible" title="添加课程" size="700px" @cancel="$emit('close')" @confirm="confirm">
    <courseForm ref="courseFormRef" />
  </sc-drawer>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { ElMessage, ElNotification } from 'element-plus';
import courseForm from "@/views/teach/course/course-form/index.vue";
const { proxy } = getCurrentInstance();

const courseFormRef = ref(null)
const visible = ref(true);

// 验证必填
const verifySubmit = () => {
  const sureData = courseFormRef.value.courseFormState
	let isOk = true
	let messageInfo = ""
	if (!sureData.name) {
		isOk = false
		messageInfo = "请输入课程名称"
		tipsFun(messageInfo)
	}
	if (!sureData.validity) {
		isOk = false
		messageInfo = "请输入有效期"
		tipsFun(messageInfo)
	}
	return isOk;
}
// 提示
const tipsFun = (messageInfo) => {
	ElNotification({
		title: '提示',
		message: messageInfo,
		type: 'warning',
		duration: 1000,
	})
}

// 保存添加
function confirm() {
  if(!verifySubmit()){return}
  console.log(courseFormRef.value.courseFormState);

  if (!courseFormRef.value.courseFormState.propagandize) {
    delete(courseFormRef.value.courseFormState.propagandize)
  }
  if (courseFormRef.value.courseFormState.outlines.length > 0) {
    courseFormRef.value.courseFormState.outlines.forEach((item, index) => {
      item.times = index + 1
    })
  }
  if (courseFormRef.value.courseFormState.tools.length > 0) {
    courseFormRef.value.courseFormState.tools.forEach((item, index) => {
      item.order = index
    })
  }
  const formData = new FormData()
  Object.entries(courseFormRef.value.courseFormState).forEach(([key, value]) => {
    if (key === 'tools' || key == 'outlines') {
      for (let i = 0; i < value.length; i++) {
        for (const keys in value[i]) {
          console.log(value[i][keys], 400, keys, value[i]);
          formData.append(`${key}[${i}].${keys}`, value[i][keys])
        }
      }
      // formData.append(key, JSON.stringify(value)) 
    } else {
      formData.append(key, value)
    }
  })
  console.log(formData);

  for (const [key, value] of formData.entries()) {
    console.log(key, value)
  }
  proxy.$API.course.course.post(formData).then(res => {
    visible.value = false
    ElMessage({
      message: res.message,
      type: 'success',
    })
  })
}
</script>

<style lang="scss" scoped>
.mr10 {
  margin-right: 10px;
}
</style>
